﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Common;
using Common.Handle;
using Common.Server;
using SuperSocket.SocketBase;

namespace ChannelServer.Server
{
    public class ChannelServer
    {
        private static ChannelServer m_instance;
        private MapleServer m_Server;

        /// <summary>
        /// 存放包头
        /// </summary>
        private PacketProcessor m_Processor;

        public static ChannelServer Instance
        {
            get
            {
                return m_instance;
            }
        }

        public ChannelServer(int port,int ID)
        {
            Console.Title = "频道服务器_"+ID;
            m_Server = new MapleServer();
            SuperSocket.SocketBase.Config.ServerConfig config = new SuperSocket.SocketBase.Config.ServerConfig();
            SuperSocket.SocketBase.Config.RootConfig LConfig = new SuperSocket.SocketBase.Config.RootConfig();
            LConfig.Isolation = IsolationMode.AppDomain;
            LConfig.PerformanceDataCollectInterval = 1000;
            config.Name = "channelServer";
            config.Port = port;
            //注册事件
            RegisterEvent();

            if (!m_Server.Setup(LConfig,config))
            {
                Console.WriteLine("端口设置失败!");
                Console.ReadKey();
                return;
            }

            //新连接事件
            m_Server.NewSessionConnected += new SessionHandler<MapleSession>(NewSessionConnected);//new SessionHandler<AppSession>(NewSessionConnected);

            //收到消息事件
            m_Server.NewRequestReceived += NewRequestReceived;//new RequestHandler<MapleSession, MpaleRequestInfo>(NewRequestReceived);

            //连接断开事件
            m_Server.SessionClosed += new SessionHandler<MapleSession, SuperSocket.SocketBase.CloseReason>(SessionClosed);

            if (!m_Server.Start())
            {
                Console.WriteLine("启动服务失败!");
                Console.ReadKey();
                return;
            }

            Console.WriteLine("频道服务器开启成功!");
            m_Server.AddChannelServer();

            while (true)
            {
                var str = Console.ReadLine();
                if (str.ToLower().Equals("exit"))
                {
                    break;
                }
            }

            Console.WriteLine();

            //停止服务
            m_Server.Stop();

            Console.WriteLine("服务已停止，按任意键退出!");
            Console.ReadKey();
        }

        /// <summary>
        /// 注册封包事件
        /// </summary>
        public void RegisterEvent()
        {
            m_Processor = new PacketProcessor();
            //m_Processor.registerHandler(RecvPacketOpcode.帐号登录, new MapleLoginHandle());
            //m_Processor.registerHandler(RecvPacketOpcode.帐号注册, new MapleRegisterUIHandle());
            //m_Processor.registerHandler(RecvPacketOpcode.帐号检测, new MapleCheckAccountsHandle());
            //m_Processor.registerHandler(RecvPacketOpcode.注册处理, new MapleRegisterHandle());
            //m_Processor.registerHandler(RecvPacketOpcode.服务器状态, new MapleServerStateHandle());

        }


        /// <summary>
        /// 用户断开连接
        /// </summary>
        /// <param name="session"></param>
        /// <param name="value"></param>
        private void SessionClosed(MapleSession session, CloseReason value)
        {
            //switch (value)
            //{
            //    case CloseReason.ClientClosing://客户端主动断开连接
            //    case CloseReason.ServerClosing://服务端主动断开客户端的连接
            //    case CloseReason.TimeOut://时间超时
            //}
            Console.WriteLine("用户:" + session.LocalEndPoint.Address + ":" + session.LocalEndPoint.Port + "断开连接   状态:" + value);
        }


        private void NewRequestReceived(MapleSession session, MpaleRequestInfo requestInfo)
        {
            if (m_Processor.GetHandler(requestInfo.PackageHead) == null)
            {
                Console.WriteLine("包头[" + requestInfo.PackageHead + "] :" + requestInfo.Buffer);
            }
            else
            {
                Console.WriteLine("[服务端]:" + "[" + requestInfo.Key + "] " + requestInfo.Buffer.ToString());
                m_Processor.GetHandler(requestInfo.PackageHead).HandlePacket(WorldServer.Server.MapleWorldServer.GetClinet(session), requestInfo.Buffer);
            }
        }

        /// <summary>
        /// 新用户连接
        /// </summary>
        /// <param name="session"></param>
        private void NewSessionConnected(MapleSession session)
        {

        }

        static void Main(string[] args)
        {
            m_instance = new ChannelServer(9596,1);
        }
    }
}
